package com.czl.module_storehouse.activity.shift.add;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.czl.base.config.AppConstants;
import com.czl.base.data.bean.tengyun.LocatListBean;
import com.czl.base.data.bean.tengyun.ProductBean;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.base.util.SpHelper;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_base.mvp.view.SimpleView;
import com.czl.module_service.event.StorehouseHomeScanBackEvent;
import com.czl.module_service.event.StorehouseHomeScanEvent;
import com.czl.module_service.system.Constants;
import com.czl.module_storehouse.R;
import com.czl.module_storehouse.activity.base.BaseOperationLocationActivity;
import com.czl.module_storehouse.activity.intostore.selectgoods.SelectGoodsActivity;
import com.czl.module_storehouse.activity.operation.SelectedProductActivity;
import com.czl.module_storehouse.activity.operation.SelectedSortActivity;
import com.czl.module_storehouse.activity.scan.ScanActivity;
import com.czl.module_storehouse.adapter.ShiftAddAdapter;
import com.czl.module_storehouse.bean.ShiftAddBean;
import com.czl.module_storehouse.bean.ShiftBean;
import com.czl.module_storehouse.databinding.ActivityShiftAddBinding;
import com.czl.module_storehouse.databinding.FooterShiftAddBinding;
import com.czl.module_storehouse.event.SelectGoodsEvent;
import com.czl.module_storehouse.event.SelectedProductEvent;
import com.czl.module_storehouse.event.SelectedProductResultEvent;
import com.czl.module_storehouse.event.ShiftEvent;
import com.czl.module_storehouse.listener.OnItemChangeListener;
import com.czl.module_storehouse.mvp.presenter.ProductPresenter;
import com.czl.module_storehouse.mvp.presenter.ShiftPresenter;
import com.czl.module_storehouse.mvp.presenter.StorehouseLocationPresenter;
import com.czl.module_storehouse.mvp.view.StorehouseLocationView;
import com.czl.module_storehouse.utils.QrCodeRuleUtils;
import com.jeremyliao.liveeventbus.LiveEventBus;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


/**
 * @author xubin
 */
@Route(path = AppConstants.Router.Service.F_SERVICE_SHIFT)
public class ShiftAddActivity extends BaseOperationLocationActivity<ActivityShiftAddBinding> implements SimpleView, StorehouseLocationView {

    private final ShiftBean mShiftBean = new ShiftBean();
    private ShiftAddAdapter mShiftAddAdapter;
    private int mSelectPosition;
    private ShiftAddBean mShiftAddBean;
    @InjectPresenter
    ProductPresenter mProductPresenter;
    @InjectPresenter
    ShiftPresenter mShiftPresenter;
    @InjectPresenter
    StorehouseLocationPresenter mStorehouseLocationPresenter;
    private boolean homeScan;
    private final ActivityResultLauncher<Intent> mLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult activityResult) {
                    if (activityResult == null || activityResult.getData() == null) {
                        return;
                    }
                    String result = activityResult.getData().getStringExtra(ScanActivity.RESULT);
                    if (mProductPresenter != null) {
                        mProductPresenter.getProductInfoByCode(QrCodeRuleUtils.handleStorehouseProductResult(result));
                    }
                }
            });
    private FooterShiftAddBinding mShiftAddBinding;

    @Override
    protected ActivityShiftAddBinding getBinding(LayoutInflater layoutInflater) {
        return ActivityShiftAddBinding.inflate(layoutInflater);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mToolBinding.toolbarContentTitle.setText("物品移位");
        mShiftAddAdapter = new ShiftAddAdapter(new ArrayList<>());
        binding.recyclerView.setAdapter(mShiftAddAdapter);

        addFooterView();
        initListener();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        LiveEventBus.get(StorehouseHomeScanEvent.class).observe(this, event -> {
            ProductBean productBean = event.getSortBean().getProductBean();
            if (productBean != null) {
                addAdapterProduct(productBean);
            } else {
                SortBean sortBean = event.getSortBean();
                if (mShiftAddBean == null) {
                    mShiftAddBean = new ShiftAddBean();
                }
                mShiftAddBean.setSortBean(sortBean);
                mShiftAddAdapter.addData(mShiftAddBean);
            }
            homeScan = true;
        });
    }

    protected void initListener() {
        mShiftAddAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.tv_loc) {
                toSelectedActivity(position);
            } else if (view.getId() == R.id.cl_root) {
                toSelectedActivity(position);
            }
        });
        mShiftAddAdapter.setOnItemChangeListener(new OnItemChangeListener() {
            @Override
            public void onChange(int position) {

            }

            @Override
            public void add(int position) {

            }

            @Override
            public void remove(int position) {
                setButtonStateByRemove();
            }
        });
        binding.btnSure.setOnClickListener(v -> submit());
        binding.headerAdd.svLeft.setOnClickListener(v -> goScanActivity());
        binding.headerAdd.svRight.setOnClickListener(v -> goSelectGoodsActivity());
    }

    private void toSelectedActivity(int position) {
        mSelectPosition = position;
        mShiftAddBean = mShiftAddAdapter.getItem(position);
        SelectedProductEvent event = new SelectedProductEvent(mShiftAddBean.getSortBean(), "移位");
        event.setMaxNum(Integer.MAX_VALUE);

        if (mShiftAddBean.getSortBean() != null) {
            if (mShiftAddBean.getSortBean().pasteCode()) {
                //单品扫码
                List<ProductBean> productList = new ArrayList<>();
                for (ShiftAddBean bean : mShiftAddAdapter.getData()) {
                    if (bean.getProductBean() != null) {
                        productList.add(bean.getProductBean());
                    }
                }
                event.setProductBeanList(productList);
                EventBus.getDefault().postSticky(event);
                startActivity(new Intent(getContext(), SelectedProductActivity.class));
            } else {
                EventBus.getDefault().postSticky(event);
                startActivity(new Intent(getContext(), SelectedSortActivity.class));
            }
        }
    }

    private void submit() {
        int shiftLocatIn = mShiftBean.getShiftLocatIn();
        if (shiftLocatIn == 0) {
            showToast("请选择移入库位");
            return;
        }
        List<ShiftAddBean> data = mShiftAddAdapter.getData();
        List<SortBean> sortBeans = new ArrayList<>();
        List<ProductBean> productBeans = new ArrayList<>();
        for (ShiftAddBean bean : data) {
            ProductBean productBean = bean.getProductBean();
            if (productBean != null) {
                productBeans.add(productBean);
            }
            SortBean sortBean = bean.getSortBean();
            if (sortBean != null) {
                sortBeans.add(sortBean);
            }
        }
        mShiftBean.setSortList(sortBeans);
        mShiftBean.setProductList(productBeans);
        if (mShiftPresenter != null) {
            mShiftPresenter.addShiftInfo(mShiftBean);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(SelectGoodsEvent event) {
        List<SortBean> sortBeanList = event.getSortBeanList();
        mShiftAddAdapter.addNewData(sortBeanList);
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(SelectedProductResultEvent event) {
        ShiftAddBean item = mShiftAddAdapter.getItem(mSelectPosition);
        mShiftAddAdapter.setData(mSelectPosition, item);
        setButtonStateByChangeData(item);
    }

    private void setButtonStateByChangeData(ShiftAddBean item) {
        //button不可点击状态
        boolean enable = false;
        if (item.getSortBean() != null) {
            if (item.getSortBean().getLocatList() != null) {
                for (LocatListBean listBean : item.getSortBean().getLocatList()) {
                    if (listBean.getShiftNum() != null && listBean.getShiftNum() > 0) {
                        enable = true;
                        break;
                    }
                }
            } else {
                enable = item.getSortBean().getProductList() != null && !item.getSortBean().getProductList().isEmpty();
            }
        }
        binding.btnSure.setEnabled(enable);
    }

    private void setButtonStateByRemove() {
        if (binding.btnSure.isEnabled()) {
            for (ShiftAddBean shiftAddBean : mShiftAddAdapter.getData()) {
                if (shiftAddBean.getProductBean() != null) {
                    return;
                } else if (shiftAddBean.getSortBean() != null && shiftAddBean.getSortBean().getLocatList() != null) {
                    for (LocatListBean listBean : shiftAddBean.getSortBean().getLocatList()) {
                        if (listBean.getShiftNum() != null && listBean.getShiftNum() > 0) {
                            return;
                        }
                    }
                }
            }
            binding.btnSure.setEnabled(false);
        }
    }

    private void addFooterView() {
        if (mShiftAddAdapter != null) {
            mShiftAddBinding = FooterShiftAddBinding.inflate(getLayoutInflater());
            mShiftAddAdapter.addFooterView(mShiftAddBinding.getRoot());
            mShiftAddBinding.tvLoc.setOnClickListener(v -> getStorehouseLocatList(true));
        }
    }

    @Override
    protected StorehouseLocationPresenter getLocationPresenter() {
        return mStorehouseLocationPresenter;
    }

    @Override
    protected boolean callBackModel(LocatListBean bean) {
        mShiftAddBinding.tvLoc.setText(bean.getStorehouseLocatName());
        mShiftBean.setShiftLocatIn(bean.getStorehouseLocatId());
        return true;
    }

    @Override
    protected void onStart() {
        super.onStart();
        /*if (mEvent != null) {
            if (SortListBeanEvent.TAG_BASE_INFO == mEvent.getTag()) {
                SortBean sortBean = mEvent.getSortBean();
                if (sortBean != null) {
                    if (mShiftAddBean == null) {
                        mShiftAddBean = new ShiftAddBean();
                    }
                    mShiftAddBean.setSortBean(sortBean);
                    mShiftAddAdapter.addData(mShiftAddBean);
                }
            }
        }*/
    }

    private void getSelectLocatList() {
        List<ProductBean> products = mShiftAddAdapter.getProducts();
        for (ProductBean bean : products) {
            mSelectedSet.add(bean.getStorehouseLocatId());
        }
        List<SortBean> sortBeans = mShiftAddAdapter.getSortBeans();
        for (SortBean bean : sortBeans) {
            List<LocatListBean> locatList = bean.getLocatList();
            if (locatList == null || locatList.isEmpty()) {
                continue;
            }
            for (LocatListBean locatListBean : locatList) {
                mSelectedSet.add(locatListBean.getStorehouseLocatId());
            }
        }
    }

    private void goSelectGoodsActivity() {
        ShiftEvent event = new ShiftEvent(mShiftAddAdapter.getSortBeans());
        EventBus.getDefault().postSticky(event);
        Intent intent = new Intent(getContext(), SelectGoodsActivity.class);
        intent.putExtra("isHiddenAddGoods", true);
        startActivity(intent);
    }

    protected void goScanActivity() {
        mLauncher.launch(new Intent(getContext(), ScanActivity.class));
    }

    @Override
    public <T> void showHttpResponse(HttpResponse<T> httpResponse) {
        super.showHttpResponse(httpResponse);
        if (ProductPresenter.TAG_PRODUCT_INFO_BY_CODE.equals(httpResponse.getRequestTag())) {
            ProductBean productBean = (ProductBean) httpResponse.getData();
            if (productBean == null) {
                return;
            }
            if (productBean.getStorehouseId() == null ||
                    productBean.getStorehouseId() != SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_ID)) {
                showToast("不是该仓位物品");
                return;
            }
            if (productBean.getStorehouseLocatId() == null || productBean.getStorehouseLocatId() <= 0) {
                showToast("该物品不存在");
                return;
            }
            addAdapterProduct(productBean);
        } else if (ShiftPresenter.TAG_SHIFT_ADD.equals(httpResponse.getRequestTag())) {
            if (HttpResponse.SUCCESS == httpResponse.getState()) {
                if (homeScan) {
                    LiveEventBus.get(StorehouseHomeScanBackEvent.class).post(new StorehouseHomeScanBackEvent());
                }
                showToast("移位成功");
                finish();
            }
        }
    }

    private void addAdapterProduct(ProductBean productBean) {
        if (productBean.getProductBean(mShiftAddAdapter.getProducts()) == null) {
            ShiftAddBean shiftAddBean = new ShiftAddBean();
            productBean.setShiftLocatOut(String.valueOf(productBean.getStorehouseLocatId()));
            shiftAddBean.setProductBean(productBean);
            mShiftAddAdapter.addData(shiftAddBean);
            binding.btnSure.setEnabled(true);
        } else {
            showToast("该物品已添加");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mShiftAddBinding != null) {
            mShiftAddBinding.unbind();
        }
    }
}
